package com.example.actordemo1.tools;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.dispatch.OnComplete;
import akka.pattern.Patterns;
import akka.util.Timeout;
import com.example.InitActorSystemRef;
import scala.concurrent.Await;
import scala.concurrent.Future;

import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FutureActor extends AbstractActor {
    @Override
    public Receive createReceive() {
        return receiveBuilder().matchAny(o->{
            getSender().tell("回复"+o,getSelf());
        }).build();
    }


    public static void main(String[] args) {
        ActorSystem actorSystem = ActorSystem.create("sys");
        ActorRef actorRef = actorSystem.actorOf(Props.create(FutureActor.class), "futureActor");
        Timeout timeout = new Timeout(2, TimeUnit.SECONDS);
        Future<Object> future  = Patterns.ask(actorRef,"hello future",timeout);

        try {
            Object result = Await.result(future, timeout.duration());
            System.out.println((String)result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        future.onComplete(new OnComplete<Object>() {
            @Override
            public void onComplete(Throwable failure, Object success) throws Throwable {
                if(failure!=null){
                    System.out.println("失败");
                }else {
                    System.out.println("成功");
                }
            }
        },actorSystem.dispatcher());




    }
}
